layui.use(['jquery'], function() {
	const $ = layui.$;

	let arr = []; // 全局变量存储商品数据
	let listShow = [];
	let ob = null;
	let sortDir = "asc";
	let sortKey = "price";
	const menu = document.querySelector(".menu-price");

	// 初始化数据加载
	function initProducts() {
		$.ajax({
			url: '/product/list', // 对应后端接口
			type: 'GET',
			dataType: 'json',
			data: {
				page: 1,
				limit: 100,
				text: null // 搜索关键词
			},
			success: function (res) {
				arr = res.data.map(item => ({
					productid: item.productid,
					name: item.productname,    // 映射字段
					price: item.price,
					descriptin: item.description,
					img: item.imgurl,
				}));
				listShow = [...arr];
				updateList();
			},
			error: function (err) {
				console.error('数据加载失败:', err);
				alert('商品加载失败，请刷新重试');
			}
		});
	}

	// 初始化页面时加载数据
	$(document).ready(function () {
		initProducts();
	});

	function updateList() {
		var htmlStr = "";
		listShow.forEach(function (item) {
			htmlStr += `
            <div>
                <a>
                    <img data-src="${item.img}" alt="">
                </a>
                <h5>${item.name}</h5>
                <p>${item.descriptin}</p>
                <span>${item.price}.00元</span>
                <button class="layui-btn layui-btn-normal buy-btn" data-productid="${item.productid}">立即购买</button>
            </div>
        `;
		});

		menu.innerHTML = htmlStr;

		bindBuyButtonEvents();

		// 重新初始化懒加载
		initLazyLoad();
	}

	// 绑定立刻购买跳转事件
	function bindBuyButtonEvents() {
		document.querySelectorAll(".buy-btn").forEach(btn => {
			btn.addEventListener("click", function () {
				const productid = this.dataset.productid;
				console.log(productid);
				window.location.href = `page/detail?productid=${productid}`;
			});
		});
	}

	// 初始化图片懒加载
	function initLazyLoad() {
		if (ob) ob.disconnect();
		ob = new IntersectionObserver(function (entries) {
			entries.forEach(function (entry) {
				if (entry.isIntersecting) {
					entry.target.src = entry.target.dataset.src;
					ob.unobserve(entry.target);
				}
			});
		}, { threshold: 0.1 });

		document.querySelectorAll(".menu-price img").forEach(img => {
			ob.observe(img);
		});
	}

	// 修改搜索逻辑
	document.forms["search"].onsubmit = function (e) {
		e.preventDefault();
		const words = this.words.value.trim().toLowerCase();
		if (words === "") {
			// 如果输入为空，显示全部商品
			listShow = [...arr];
		} else {
			// 根据关键字过滤商品列表
			listShow = arr.filter(item =>
				item.name.toLowerCase().includes(words) ||
				item.descriptin.toLowerCase().includes(words)
			);
		}
		updateList();
	};

	// 修改排序逻辑
	document.querySelectorAll("span.sort-item").forEach(item => {
		item.onclick = function () {
			// ...原有逻辑不变，但确保字段名正确
			sortKey = this.dataset.key; // 对应 price/cale/rate
			listShow.sort((a, b) =>
				sortDir === "asc" ? a[sortKey] - b[sortKey] : b[sortKey] - a[sortKey]
			);
			updateList();
		};
	});
});